package com.example.musiccommunity.UserPage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.NewsDetail;
import com.example.musiccommunity.R;
import com.example.musiccommunity.bean.News;
import com.example.musiccommunity.util.GridAdapter;
import com.example.musiccommunity.util.ImageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Fragment_News#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment_News extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Fragment_News() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment_News.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment_News newInstance(String param1, String param2) {
        Fragment_News fragment = new Fragment_News();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private EditText etQuery;
    private ImageView search;


    private GridView grid;
    BaseAdapter mAdapter = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment__news, container, false);
        grid = view.findViewById(R.id.grid);

        etQuery = view.findViewById(R.id.et_query);
        search = view.findViewById(R.id.search);
        grid = view.findViewById(R.id.grid);
        //软键盘搜索
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str=etQuery.getText().toString();
                reqString(str);
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        reqString("");
    }
    void reqString(String key){
        String url=MainActivity.ip+"/news/get?key="+key;
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //s = new String(s.getBytes("ISO-8859-1"), "UTF-8");
                //Log.d("user***********user",s.toString());
                if(s==null || s.equals("")){
                    //Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                }
                else{
                    ArrayList<News> newsArrayList =new ArrayList<>();
                    JSONObject jsonObject = null;
                    try {
                        JSONArray jsonArray = new JSONArray(s);
                        for (int i=0;i<jsonArray.length();i++){
                            jsonObject = jsonArray.getJSONObject(i);
                            String id = jsonObject.get("id").toString();
                            String img=jsonObject.get("img").toString();
                            Bitmap bit = ImageUtil.base64ToBitmap(img);
                            News n=new News(id,jsonObject.get("author").toString(),
                                    jsonObject.get("title").toString(),
                                    jsonObject.get("txt").toString(),
                                    jsonObject.get("time").toString(),
                                    new BitmapDrawable(bit));
                            newsArrayList.add(n);
                        }
                        Collections.reverse(newsArrayList);
                        mAdapter = new GridAdapter<News>(newsArrayList, R.layout.list_new) {
                            @Override
                            public void bindView(ViewHolder holder, News obj) {
                                holder.setText(R.id.title, obj.getTitle());
                                holder.setText(R.id.author, obj.getAuthor());
                                holder.setText(R.id.time, obj.getTime());
                                holder.setImageBgResource(R.id.img,obj.getImg());
                            }

                        };
                        grid.setAdapter(mAdapter);
                        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent();
                                intent.putExtra("id",newsArrayList.get(i).getId());
                                intent.setClass(getContext() , NewsDetail.class);
                                startActivity(intent);
                            }
                        });

                    } catch (JSONException e) {
                        System.out.println(e.toString());
                        throw new RuntimeException(e);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                //Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        MainActivity.requestQueue.add(stringRequest);

    }

}